import templatesData from './templates-data.json'

// Template metadata and file loading system
export type ProjectTemplate = {
  id: string
  label: string
  description: string
  files: Record<string, string>
  defaultActiveFile: string
  suggestions?: string[]
}

// Stacks: allow composing a frontend and backend into one project
export const FRONTEND_TEMPLATE_IDS = ['next_stack', 'react_stack'] as const
export const BACKEND_TEMPLATE_IDS = [
  'express',
  'fastapi',
  'flask',
  'hono',
] as const

// Load prebuilt templates from JSON generated by scripts/build-templates.js
const templatesFromJson: ProjectTemplate[] =
  templatesData as unknown as ProjectTemplate[]

// Export the built templates
export const TEMPLATES: ProjectTemplate[] = templatesFromJson

// Get template by ID
export function getTemplateById(id: string): ProjectTemplate | undefined {
  return TEMPLATES.find((t) => t.id === id)
}

// -----------------------------
// Stack composition helpers
// -----------------------------

export function isStackId(id: string): boolean {
  return typeof id === 'string' && id.startsWith('stack:')
}

function parseStackId(
  id: string
): { frontendId: string; backendId: string } | null {
  if (!isStackId(id)) return null
  const rest = id.slice('stack:'.length)
  const [frontendId, backendId] = rest.split('+')
  if (!frontendId || !backendId) return null
  return { frontendId, backendId }
}

export function composeStack(
  frontendId: string,
  backendId: string
): ProjectTemplate | undefined {
  const frontend = getTemplateById(frontendId)
  const backend = getTemplateById(backendId)
  if (!frontend || !backend) return undefined

  const files: Record<string, string> = {}
  for (const [p, c] of Object.entries(frontend.files)) {
    files[`frontend/${p}`] = c as string
  }
  for (const [p, c] of Object.entries(backend.files)) {
    files[`backend/${p}`] = c as string
  }

  // No UI injection here; stack-specific frontends handle connectivity checks

  const backendDefault = `backend/${backend.defaultActiveFile}`
  const frontendDefault = `frontend/${frontend.defaultActiveFile}`
  const defaultActiveFile =
    backendDefault in files
      ? backendDefault
      : frontendDefault in files
      ? frontendDefault
      : Object.keys(files)[0] || 'README.md'

  // For stacks, keep suggestions concise: prefer backend-only prompts
  const suggestions = backend.suggestions
    ? [...backend.suggestions]
    : frontend.suggestions
    ? [...frontend.suggestions]
    : undefined

  return {
    id: `stack:${frontend.id}+${backend.id}`,
    label: `${frontend.label} + ${backend.label}`,
    description: 'Custom stack (composed frontend and backend)',
    files,
    defaultActiveFile,
    suggestions,
  }
}

export function getStackById(id: string): ProjectTemplate | undefined {
  const parsed = parseStackId(id)
  if (!parsed) return undefined
  return composeStack(parsed.frontendId, parsed.backendId)
}
